from django.shortcuts import render, HttpResponse
import requests, re, time
import json
from util import utils

headers = {
	"Referer": "https://wx.qq.com/",
	"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/"
				  "68.0.3440.84 Safari/537.36",
}


def login(req):
	# https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_=1533173881930
	unix_time = utils.cur_time()
	uuid_url = "https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-" \
			   "bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_={0}".format(unix_time)
	uuid_ret = requests.get(url=uuid_url,
				 headers=headers).text
	uuid = re.findall('uuid = "(.*)"', uuid_ret)[0]
	req.session['UUID_TIME'] = unix_time
	req.session['UUID'] = uuid
	return render(req, 'login.html', {'uuid':uuid})

def check_login(req):
	ret = {'code':408}
	base_login_url = 'https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip=0&' \
		  'r=127900166&_={1}'.format(req.session['UUID'],utils.cur_time())
	r1 = requests.get(url=base_login_url,
				 headers=headers)

	if "window.code=408" in r1.text:
		ret['code'] = 408
	elif "window.code=201" in r1.text:
		ret['code'] = 201
		ret['data'] = re.findall("userAvatar = '(.*)'",r1.text)[0]
	elif "window.code=200" in r1.text:
		req.session['LOGIN_COOKIE'] = r1.cookies.get_dict()
		ret['code'] = 200
		base_redirect_url = re.findall('redirect_uri="(.*)"',r1.text)[0]
		redirect_url = base_redirect_url + '&fun=new&version=v2&l'  # fetch pass-ticket
		r2 = requests.get(url=redirect_url,
					 headers=headers,
					 cookies=r1.cookies.get_dict())
		# req.session['LOGIN_COOKIE'].update(r2.cookies.get_dict())
		pass_ticket_dict = utils.ticket(r2.text)
		pass_ticket = pass_ticket_dict['pass_ticket']
		req.session['TICKET_DCIT'] = pass_ticket_dict
		req.session['TICKET_COOKIE'] = r2.cookies.get_dict()

		# 初始化
		post_data = {
			"BaseRequest":{"Uin":pass_ticket_dict['wxuin'],
						   "Sid":pass_ticket_dict['wxsid'],
						   "Skey":pass_ticket_dict['skey'],
						   "DeviceID":"e675598960475433"}
		}
		init_url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=127945986&lang=zh_CN&pass_ticket={0}".format(pass_ticket)
		r3 = requests.post(
			url=init_url,
			headers=headers,
			json=post_data
		)

		r3.encoding='utf-8'
		# with open('init_data.txt','wb') as f:
		# 	f.write(r3.content)
		init_dict = json.loads(r3.text)
		req.session['INIT_DICT'] = init_dict
	return HttpResponse(json.dumps(ret))

def avatar(req):
	# url = "https://wx.qq.com" + req.session['INIT_DICT']['User']['HeadImgUrl']
	# "/cgi-bin/mmwebwx-bin/webwxgeticon?seq=837888523&username=@00a75f4d8559e1060b6ae98eba277c92f201d50ff00849bd3948ddb85dd3e102&skey=@crypt_90708ce0_2a1b4b4c491df4e3e1f7e332b2364f67"
	# Accept: image/webp,image/apng,image/*,*/*;q=0.8
	headers['Accept'] = 'image/webp,image/apng,image/*,*/*;q=0.8'
	cookies = {}
	cookies.update(req.session['LOGIN_COOKIE'])
	cookies.update(req.session['TICKET_COOKIE'])
	url = "https://wx.qq.com{0}&username={1}&skey={2}".format(req.GET.get('imgUrl'), req.GET.get('username'), req.GET.get('skey'))
	res = requests.get(
		url=url,
		headers=headers, #{'Content-Type':'image/jpeg'},
		cookies=cookies
	)
	# print(res.content)
	# print(url)
	# print(req.GET.get('username'))
	# print(req.session['INIT_COOKIE'])
	return HttpResponse(res.content)

def index(req):
	return render(req,'index.html')

def contact_list(req):
	base_url = "https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=zh_CN&r={0}&seq=0" \
			   "&skey={1}"
	url = base_url.format(utils.cur_time(),req.session['TICKET_DCIT']['skey'])
	cookies = req.session['TICKET_COOKIE']
	r4 = requests.get(
		url=url,
		headers=headers,
		cookies=cookies
	)
	r4.encoding = 'utf-8'
	# print(r4.text)
	# with open('contact_list.txt','wb') as f:
	# 	f.write(r4.content)
	user_list = json.loads(r4.text)  # 将str转换为dict
	# print(type(user_list))
	return render(req, 'contact_list.html', {'contact_res':user_list})

def send_msg(req):
	"""
	发送消息
	:param req:
	:return:
	"""
	current_user = req.session['INIT_DICT']['User']['UserName']
	to = req.POST.get('to')
	msg = req.POST.get('msg')
	cookies = req.session['TICKET_COOKIE']
	# https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg
	# Content-Type: application/json;charset=UTF-8
	# "Uin": pass_ticket_dict['wxuin'],
	# "Sid": pass_ticket_dict['wxsid'],
	# "Skey": pass_ticket_dict['skey'],
	# "DeviceID": "e675598960475433"}
	post_data = {
		"BaseRequest": {
			"Uin": req.session['TICKET_DCIT']['wxuin'],
			"Sid": req.session['TICKET_DCIT']['wxsid'],
			"Skey": req.session['TICKET_DCIT']['skey'],
			"DeviceID": "e675598960475433"
		},
		"Msg": {
			"Type": 1,
			"Content": msg,
			"FromUserName": current_user,
			"ToUserName": to,
			"LocalID": utils.cur_time(),
			"ClientMsgId": utils.cur_time()
		},
		"Scene": 0
	}
	r4 = requests.post(
		url='https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg',
		data=json.dumps(post_data,ensure_ascii=False).encode('utf-8'),
		headers=headers,
		cookies = cookies
	)
# 	返回值 如下
	# {
# "BaseResponse": {
# "Ret": 0,
# "ErrMsg": ""
# }
# ,
# "MsgID": "4270497712300995818",
# "LocalID": "1533366384885"
# }
	return HttpResponse('已发送！')

def get_msg(req):
	# https://webpush.wx.qq.com/cgi-bin/mmwebwx-bin/synccheck?r=1533366711902&skey=%40crypt_90708ce0_deebfb0b39a802b7f695499db58dc039&sid=%2BiLvIrWAAZ5FwXV0&uin=393027208&deviceid=e595813278426913&synckey=1_688698397%7C2_688698530%7C3_688698493%7C11_688698431%7C201_1533366710%7C203_1533354366%7C1000_1533358831%7C1001_1533358993&_=1533354188116
	sync_check_url = 'https://webpush.wx.qq.com/cgi-bin/mmwebwx-bin/synccheck'
	synckey_list = req.session['INIT_DICT']['SyncKey']['List']  #是一个LIST
	synckey = []
	cookies = req.session['TICKET_COOKIE']
	for item in synckey_list:
		tmp = "%s_%s" % ( item['Key'], item['Val'])
		synckey.append(tmp)
	synckey = '|'.join(synckey)
	params = {
		'r': utils.cur_time(),
		'skey': req.session['TICKET_DCIT']['skey'],
		'uin': req.session['TICKET_DCIT']['wxuin'],
		'sid': req.session['TICKET_DCIT']['wxsid'],
		'deviceid': 'e675598960475433',
		'_': utils.cur_time(),
		'synckey': synckey
	}
	r1 = requests.get(
		url=sync_check_url,
		params=params,
		headers=headers,
		cookies = cookies
	)

	# r1.encoding='utf-8'
	# window.synccheck={retcode:"0",selector:"0"}
	if '{retcode:"0",selector:"0"}' in r1.text:
		print('selector:0')
		return HttpResponse('0000')
	# elif '{retcode:"0",selector:"2"}' in r1.text:
	# 	print('selector 2')
		# 有消息
		# https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsync?sid=+iLvIrWAAZ5FwXV0&skey=@crypt_90708ce0_deebfb0b39a802b7f695499db58dc039
		# {"BaseRequest":{"Uin":393027208,"Sid":"+iLvIrWAAZ5FwXV0","Skey":"@crypt_90708ce0_deebfb0b39a802b7f695499db58dc039","DeviceID":"e802688391980592"},"SyncKey":{"Count":8,"List":[{"Key":1,"Val":688698579},{"Key":2,"Val":688698594},{"Key":3,"Val":688698533},{"Key":11,"Val":688698431},{"Key":201,"Val":1533373210},{"Key":203,"Val":1533354366},{"Key":1000,"Val":1533369843},{"Key":1001,"Val":1533370034}]},"rr":-70069546}
	base_post_url = 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsync?sid={0}&skey={1}'
	post_url = base_post_url.format(req.session['TICKET_DCIT']['skey'], req.session['TICKET_DCIT']['skey'])

	post_data = {
		"BaseRequest": {
			"Uin": req.session['TICKET_DCIT']['wxuin'],
			"Sid": req.session['TICKET_DCIT']['wxsid'],
			"Skey": req.session['TICKET_DCIT']['skey'],
			"DeviceID": "e675598960475433"
		},
		"SyncKey": req.session['INIT_DICT']['SyncKey'],
		"rr": -70069546
	}

	r2 = requests.post(
		url=post_url,
		json=post_data,
		cookies = cookies
	)

	# 接收到消息： synckey要更新
	r2.encoding='utf-8'
	msg_dict = json.loads(r2.text)
	# print(msg_dict)
	for msg in msg_dict['AddMsgList']:
		Content = msg['Content']
		# CreateTime = msg['CreateTime']
		# FromUserName =msg['FromUserName']
		print('new message', Content)

	print('1',req.session['INIT_DICT']['SyncKey'])
	init_dict = req.session['INIT_DICT']
	init_dict['SyncKey'] = msg_dict['SyncKey']
	print('2',req.session['INIT_DICT']['SyncKey'])
	req.session['INIT_DICT'] = init_dict
	# print('3', req.session['INIT_DICT'])
	return HttpResponse('haha')